import cv2
import numpy as np

curshape = 0
start_point = (0, 0)

# 显示窗口和背景 第一个高 宽
img = np.zeros((640, 480, 3), np.uint8)

def draw_shape(start_point, end_point, shape):
    if shape == 1:
        cv2.line(img, start_point, end_point, (0, 0, 255), 2)
    elif shape == 2:
        cv2.rectangle(img, start_point, end_point, (0, 255, 0), 2)
    elif shape == 3:
        center = (int((start_point[0] + end_point[0]) / 2), int((start_point[1] + end_point[1]) / 2))
        radius = int(np.sqrt((center[0] - start_point[0]) ** 2 + (center[1] - start_point[1]) ** 2))
        cv2.circle(img, center, radius, (255, 0, 0), 2)

def mouse_callback(event, x, y, flags, userdata):
    global curshape, start_point
    if event & cv2.EVENT_LBUTTONDOWN == cv2.EVENT_LBUTTONDOWN:
        start_point = (x, y)
    elif event & cv2.EVENT_LBUTTONUP == cv2.EVENT_LBUTTONUP:
        draw_shape(start_point, (x, y), curshape)

# 创建窗口
cv2.namedWindow('drawshape', cv2.WINDOW_NORMAL)

# 设置鼠标回调
cv2.setMouseCallback('drawshape', mouse_callback)

while True:
    cv2.imshow('drawshape', img)
    key = cv2.waitKey(1) & 0xFF
    if key == ord('q'):
        break
    elif key == ord('l'):
        curshape = 1
        print("画线")
    elif key == ord('r'):
        curshape = 2
        print("画矩形")
    elif key == ord('c'):
        curshape = 3
        print("画圆")

# 释放窗口资源
cv2.destroyAllWindows()